package com.jintoufs.util;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import com.jhj.common.util.JhjCookieUtil;

/**
 * 与请求相关的工具类
 * 
 * @author fuhuo.zhang
 * @since 2015-3-19
 */
public final class RequestUtil {
    
    private RequestUtil() {
    }
    
    /**
     * 从reuqest的cookie中获取对应的参数，封装保存入指定的类型对象
     * 
     * @param request 
     * @param obj 存入封装数据的对象
     * @param prefix cookie的前缀，cookie名称为  prefix + 属性名称
     */
    public static void getParamtersFromCookie(HttpServletRequest request, Object obj, String prefix) {
        if(obj == null ){
            throw new IllegalArgumentException("存储封装的对象不能为null");
        }
        if(prefix == null){
            prefix = "";
        }
        Class<?> clazz = obj.getClass();
        Field[] fields = clazz.getDeclaredFields();
        for (Field f : fields) {
            if (isNotBeanFiled(f)) {
                // final or static field
                continue;
            }
            String fieldName = f.getName();
            Class<?> c = (Class<?>) f.getGenericType();
            String s = JhjCookieUtil.getValue(prefix + fieldName, request);
            Object value = parseString(s, c);
            f.setAccessible(true);
            try {
                f.set(obj, value);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }
    }
    
    /**
     * 该属性不是final 或 static的
     * 
     * @param field
     * @return
     */
    private static boolean isNotBeanFiled(Field field) {
        int mod = field.getModifiers();
        return Modifier.FINAL == (mod & Modifier.FINAL) || Modifier.STATIC == (mod & Modifier.STATIC);
    }
    
    /**
     * 把字符画转换为指定的类型<br>
     * 调用指定类型的静态方法valueOf(String s) 方法进行转换 <br>
     * 如： Integer.valueOf("10")
     * 
     * @param s
     * @param clazz
     * @return 返回指定类型，如果类型不存在valueOf(String s)静态方法，返回原字符串
     */
    public static Object parseString(String s, Class<?> clazz) {
        try {
            Method m = clazz.getDeclaredMethod("valueOf", s.getClass());
            return m.invoke(null, s); // static method
        } catch (Exception e) {
            return s;
        }
    }
    
    /**
     * pid.num|pid.num
     * k-pid  v-num
     * @param request
     * @param cookieKey
     * @return 未成功解析时返回空Map
     */
    public static Map<Integer,Integer> paresePidAndNumString(HttpServletRequest request, String cookieKey){
        Map<Integer,Integer> map = new HashMap<Integer, Integer>();
        // 目前存一个 pid.num|pid.num  预留多个商品时
        String pidAndNums = JhjCookieUtil.getValue(cookieKey, request);
        if(pidAndNums==null || "".equals(pidAndNums)){
            return map;
        }
        
        String[] arrPidAndNum = pidAndNums.split("\\|");
        
        for(String s : arrPidAndNum){
            String[] pon = s.split("\\."); 
            int len = pon.length;
            if(len<2){
                //.分割不够2个，没有pid.num
                continue;
            }
            int skuId = Integer.parseInt(pon[0]);
            int skuNum = Integer.parseInt(pon[1]);
            if(skuId<1 || skuNum<1){
                //不是有效的skuId或skuNum
                continue;
            }
            map.put(skuId, skuNum);
        }
        
        return map;
    }
    public static boolean isAjaxRequest(HttpServletRequest request){
        return (request.getHeader("X-Requested-With") != null)&&("XMLHttpRequest".equals(request.getHeader("X-Requested-With").toString()));
    }
}
